package com.gitee.hermer.engine.jars.app.sdk.configuration;

import java.util.Map;

import org.springframework.beans.factory.BeanCreationException;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ImportAware;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.AnnotationAttributes;
import org.springframework.core.type.AnnotationMetadata;
import org.springframework.stereotype.Component;

import com.gitee.hermer.engine.jars.app.sdk.EngineApplicationRefreshBeanEvent;
import com.gitee.hermer.engine.jars.app.sdk.annotate.EnableEngineScan;
import com.gitee.hermer.engine.jars.app.sdk.processor.EngineJobBeanFactoryPostProcessor;
import com.gitee.hermer.engine.jars.core.app.domain.EngineAppJobContext;

@Configuration
public class EngineAppAutoConfiguration implements ImportAware,Ordered{

	private AnnotationAttributes metadataAttributes;

	@Override
	public void setImportMetadata(AnnotationMetadata importMetadata) {
		if(importMetadata != null){
			Map<String, Object> attributes = importMetadata.getAnnotationAttributes(EnableEngineScan.class.getName(), false);
			this.metadataAttributes = AnnotationAttributes.fromMap(attributes);
		}
	}

	@Bean
	public EngineApplicationRefreshBeanEvent engineApplicationRefreshBeanEvent(){
		return new EngineApplicationRefreshBeanEvent();
	}

	@Bean
	public EngineAppJobContext appJobContext(){
		return new EngineAppJobContext(null);
	}
	
	@Bean
	public EngineJobBeanFactoryPostProcessor engineJobBeanFactoryPostProcessor(){
		if(metadataAttributes == null)
			throw new BeanCreationException("not find @EngineComponentScan attributes");
		return new EngineJobBeanFactoryPostProcessor(metadataAttributes.getStringArray("basePackages"));
	}

	@Override
	public int getOrder() {
		return LOWEST_PRECEDENCE + 500;
	}


}
